﻿#include"XQListSearchWidget.h"
#include<QListWidget>
#include<QLineEdit>
#include<QDateTime>
#include<QDebug>
XQListSearchWidget::XQListSearchWidget(QWidget* parent)
	:QWidget(parent)
{
	init();
}

XQListSearchWidget::~XQListSearchWidget()
{
	if (m_startTime != nullptr)
		delete m_startTime;
	/*qInfo() << "释放";*/
}

bool XQListSearchWidget::activityAutoClose() const
{
	return m_AutoClose;
}

QStringList& XQListSearchWidget::database()
{
	return m_database;
}

QStringList& XQListSearchWidget::selectedData()
{
	return m_selectedData;
}

size_t XQListSearchWidget::testingTime() const
{
	return m_testingTime;
}

void XQListSearchWidget::setDatabase(const QStringList& data)
{
	m_database = data;
	if (m_search->text().isEmpty())
	{
		m_listWidget->clear();
		m_listWidget->addItems(m_database);
	}
}

void XQListSearchWidget::setSelectedData(const QStringList& data)
{
	m_selectedData = data;
}

void XQListSearchWidget::setTestingTime(size_t time)
{
	m_testingTime = time;
}

void XQListSearchWidget::setChangeList()
{
	if (m_search->text().isEmpty())//空的输入框所以插入全部
	{
		m_listWidget->clear();//清空列表重新插入
		m_listWidget->addItems(m_database);
		return;
	}
	QDateTime endTime = QDateTime::currentDateTime();
	if (m_startTime->msecsTo(endTime) < m_testingTime)
		return;//时间没到直接跳出
	//根据输入框的值遍历数据
	m_listWidget->clear();//清空列表重新插入
	QSet<QString> setStr;//防止重复
	QString str = m_search->text();
	//获取编辑框字符串的所有字串
	for (int len = str.length(); len > 0; --len) {
		for (int i = 0; i <= str.length() - len; ++i) {
			QString subStr = str.mid(i, len);
			setStr << subStr;
		}
	}
	//排序
	QStringList subStrList;//编辑框中的所有字串
	for (auto& text:setStr)
	{
		subStrList << text;
	}
	std::sort(subStrList.begin(), subStrList.end(), [](const QString& s1, const QString& s2) {
		return s1.length() > s2.length(); // 从长到短排序
		});
	//qInfo() << subStrList;
	for (auto& str:m_database)
	{
		for (auto& text : subStrList)
		{
			if (str.indexOf(text) != -1)
			{
				m_listWidget->addItem(str);
				break;//加入后遍历下一个数据
			}
		}
	}
	*m_startTime = endTime;//时间重新开始
}

void XQListSearchWidget::setActivityAutoClose(bool flag)
{
	m_AutoClose = flag;
}
